package com.zhss.demo.concurrent;

import java.util.concurrent.*;

/**
 * @author xuhua
 * @create 2021-11-27 17:50
 * @description 测试线程interrupt案例1
 */
public class InterruptDemo {
    public static void main(String[] args) throws Exception {
        MyThread thread = new MyThread();
        thread.start();

        Thread.sleep(1000);

        
        /**
         *  整体思路：线程启动shouldRun为true，线程执行同时进入休眠，将线程shouldRun至为fals，同时打断线程休眠
         *  再次运行运行时发线shouldRun为fals，线程不在执行
         */

        // 将线程调用标识转换为false
        thread.setShouldRun(false);
        // 打断线程休眠
        thread.interrupt();
    }

    private static class MyThread extends Thread {

        private Boolean shouldRun = true;

        @Override
        public void run() {
            while(shouldRun) {
                try {
                    System.out.println("线程1在执行工作......");
                    Thread.sleep(30 * 1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        public void setShouldRun(Boolean shouldRun) {
            this.shouldRun = shouldRun;
        }

    }
}
